<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>获取授权码</title>
  <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    /* 样式保持不变 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Noto Sans SC', sans-serif;
    }

    body {
      background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f1 100%);
      min-height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px;
    }

    .auth-container {
      width: 100%;
      max-width: 500px;
      background: white;
      border-radius: 16px;
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }

    .auth-header {
      background: linear-gradient(90deg, #4361ee 0%, #3a0ca3 100%);
      color: white;
      padding: 30px;
      text-align: center;
      position: relative;
    }

    .auth-header h1 {
      font-size: 28px;
      margin-bottom: 10px;
    }

    .auth-header p {
      opacity: 0.9;
      font-size: 16px;
    }

    .login-form {
      padding: 30px;
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: #495057;
    }

    .input-with-icon {
      position: relative;
    }

    .input-with-icon i {
      position: absolute;
      left: 15px;
      top: 50%;
      transform: translateY(-50%);
      color: #6c757d;
    }

    .form-input {
      width: 100%;
      padding: 14px 14px 14px 45px;
      border: 1px solid #ced4da;
      border-radius: 8px;
      font-size: 16px;
      transition: all 0.3s;
    }

    .form-input:focus {
      outline: none;
      border-color: #4361ee;
      box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.15);
    }

    .login-btn {
      width: 100%;
      background: linear-gradient(90deg, #4361ee 0%, #3a0ca3 100%);
      color: white;
      border: none;
      padding: 14px;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s ease;
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
    }

    .login-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(67, 97, 238, 0.3);
    }

    .login-btn:disabled {
      background: #adb5bd;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }

    .forgot-password {
      text-align: right;
      margin-top: 5px;
    }

    .forgot-password a {
      color: #4361ee;
      text-decoration: none;
      font-size: 14px;
    }

    .code-section {
      background: #f8f9fa;
      border-radius: 12px;
      padding: 25px;
      text-align: center;
      margin: 25px 0;
      border: 1px dashed #e9ecef;
      display: none;
    }

    .code-title {
      color: #6c757d;
      margin-bottom: 15px;
      font-size: 16px;
    }

    .auth-code {
      font-size: 32px;
      font-weight: 700;
      letter-spacing: 2px;
      background: white;
      padding: 15px 25px;
      border-radius: 10px;
      display: inline-block;
      color: #3a0ca3;
      border: 1px solid #e9ecef;
      font-family: monospace;
      margin: 10px 0;
    }

    .expiry-info {
      display: flex;
      justify-content: center;
      gap: 20px;
      margin-top: 15px;
      color: #6c757d;
      font-size: 14px;
    }

    .info-item {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .info-value {
      font-weight: 600;
      color: #3a0ca3;
      margin-top: 5px;
    }

    .action-section {
      display: flex;
      flex-direction: column;
      gap: 15px;
      display: none;
    }

    .action-btn {
      background: linear-gradient(90deg, #4361ee 0%, #3a0ca3 100%);
      color: white;
      border: none;
      padding: 16px;
      border-radius: 10px;
      font-size: 16px;
      font-weight: 500;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
      transition: all 0.3s ease;
    }

    .action-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(67, 97, 238, 0.3);
    }

    .action-btn.secondary {
      background: #f8f9fa;
      color: #495057;
      border: 1px solid #e9ecef;
    }

    .action-btn.secondary:hover {
      background: #f1f3f5;
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
    }

    .loading-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px;
      display: none;
    }

    .spinner {
      width: 50px;
      height: 50px;
      border: 5px solid rgba(67, 97, 238, 0.2);
      border-top: 5px solid #4361ee;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20px;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .loading-text {
      color: #6c757d;
      font-size: 16px;
    }

    .error-section {
      background: #fff5f5;
      border: 1px solid #ffecec;
      border-radius: 12px;
      padding: 25px;
      text-align: center;
      margin-bottom: 25px;
      display: none;
    }

    .error-icon {
      font-size: 48px;
      color: #ef476f;
      margin-bottom: 15px;
    }

    .error-title {
      color: #ef476f;
      font-size: 20px;
      margin-bottom: 10px;
    }

    .error-message {
      color: #6c757d;
      margin-bottom: 20px;
      white-space: pre-wrap; /* 确保错误信息换行 */
      word-break: break-word; /* 长单词自动换行 */
      text-align: left; /* 左对齐更易读 */
      background: #fff;
      padding: 15px;
      border-radius: 8px;
      font-family: monospace;
      max-height: 200px;
      overflow-y: auto;
    }

    .instructions {
      background: #f0f4ff;
      border-left: 4px solid #4361ee;
      padding: 20px;
      border-radius: 0 10px 10px 0;
      margin-top: 30px;
      display: none;
    }

    .instructions h3 {
      color: #3a0ca3;
      margin-bottom: 15px;
      font-size: 18px;
    }

    .instructions ol {
      padding-left: 20px;
    }

    .instructions li {
      margin-bottom: 10px;
      line-height: 1.6;
    }

    .footer {
      text-align: center;
      padding: 20px;
      color: #6c757d;
      font-size: 14px;
      border-top: 1px solid #f1f3f5;
    }

    .brand-logo {
      position: absolute;
      top: 20px;
      right: 20px;
      width: 60px;
      height: 60px;
      background: white;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      font-weight: bold;
      color: #4361ee;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }

    .password-toggle {
      position: absolute;
      right: 15px;
      top: 50%;
      transform: translateY(-50%);
      color: #6c757d;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div class="auth-container">
    <div class="auth-header">
      <div class="brand-logo">
        <i class="fas fa-key"></i>
      </div>
      <h1>获取您的授权码</h1>
      <p>请先验证您的身份</p>
    </div>

    <div class="login-form">
      <div class="form-group">
        <label for="username">用户名</label>
        <div class="input-with-icon">
          <i class="fas fa-user"></i>
          <input type="text" id="username" class="form-input" placeholder="请输入用户名" autocomplete="username">
        </div>
      </div>

      <div class="form-group">
        <label for="password">密码</label>
        <div class="input-with-icon">
          <i class="fas fa-lock"></i>
          <input type="password" id="password" class="form-input" placeholder="请输入密码" autocomplete="current-password">
          <span class="password-toggle" id="passwordToggle">
            <i class="fas fa-eye"></i>
          </span>
        </div>
      </div>

      <button id="loginBtn" class="login-btn">
        <i class="fas fa-key"></i> 获取授权码
      </button>

      <div id="loadingSection" class="loading-section">
        <div class="spinner"></div>
        <p class="loading-text">正在验证您的身份并生成授权码...</p>
      </div>

      <div id="errorSection" class="error-section">
        <div class="error-icon">⚠️</div>
        <h3 class="error-title">验证失败</h3>
        <p class="error-message" id="errorMessage">用户名或密码不正确</p>
        <button class="action-btn" id="retryButton">
          <i class="fas fa-redo"></i> 重试
        </button>
      </div>

      <div id="successSection">
        <div class="code-section">
          <p class="code-title">您的专属授权码</p>
          <div class="auth-code" id="authCode"></div>
          <div class="expiry-info">
            <div class="info-item">
              <span>有效期</span>
              <span class="info-value">30分钟</span>
            </div>
            <div class="info-item">
              <span>生成时间</span>
              <span class="info-value" id="generationTime"></span>
            </div>
          </div>
        </div>

        <div class="action-section">
          <button class="action-btn" id="copyButton">
            <i class="fas fa-copy"></i> 复制授权码
          </button>
          <button class="action-btn secondary" id="newCodeButton">
            <i class="fas fa-sync"></i> 获取新授权码
          </button>
        </div>

        <div class="instructions">
          <h3>如何使用授权码？</h3>
          <ol>
            <li>返回您的应用程序</li>
            <li>在授权码输入框中粘贴此代码</li>
            <li>完成账号绑定流程</li>
            <li>授权码将在30分钟后失效</li>
          </ol>
        </div>
      </div>
    </div>

    <div class="footer">
      <p> 安全授权服务 | 保护您的账号安全</p>
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // 获取元素引用
      const loginBtn = document.getElementById('loginBtn');
      const usernameInput = document.getElementById('username');
      const passwordInput = document.getElementById('password');
      const passwordToggle = document.getElementById('passwordToggle');
      const loadingSection = document.getElementById('loadingSection');
      const errorSection = document.getElementById('errorSection');
      const successSection = document.getElementById('successSection');
      const codeSection = document.querySelector('.code-section');
      const actionSection = document.querySelector('.action-section');
      const instructions = document.querySelector('.instructions');
      const authCodeElement = document.getElementById('authCode');
      const generationTimeElement = document.getElementById('generationTime');
      const errorMessageElement = document.getElementById('errorMessage');
      const retryButton = document.getElementById('retryButton');
      const copyButton = document.getElementById('copyButton');
      const newCodeButton = document.getElementById('newCodeButton');

      // 初始状态设置
      errorSection.style.display = 'none';
      loadingSection.style.display = 'none';
      codeSection.style.display = 'none';
      actionSection.style.display = 'none';
      instructions.style.display = 'none';

      // 密码显示/隐藏切换
      passwordToggle.addEventListener('click', function() {
        if (passwordInput.type === 'password') {
          passwordInput.type = 'text';
          passwordToggle.innerHTML = '<i class="fas fa-eye-slash"></i>';
        } else {
          passwordInput.type = 'password';
          passwordToggle.innerHTML = '<i class="fas fa-eye"></i>';
        }
      });

      // 获取授权码按钮事件
      loginBtn.addEventListener('click', function() {
        const username = usernameInput.value.trim();
        const password = passwordInput.value;

        if (!username || !password) {
          showError('请输入用户名和密码');
          return;
        }

        // 显示加载状态
        showLoading();

        // 获取授权码
        getAuthorizationCode(username);
      });

      // 获取授权码函数 - 改进错误处理
      async function getAuthorizationCode(userId) {
        try {
          // 显示加载状态
          showLoading();

          // 调用API获取授权码
          const response = await fetch('/auth/getAuthorizationCode', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ userId: userId })
          });

          // 检查响应状态
          if (!response.ok) {
            // 尝试解析错误信息
            let errorMsg = `请求失败 (状态码: ${response.status})`;

            try {
              // 尝试解析JSON格式的错误响应
              const errorData = await response.json();
              if (errorData.error) {
                errorMsg += `: ${errorData.error}`;
              } else if (errorData.message) {
                errorMsg += `: ${errorData.message}`;
              }
            } catch (jsonError) {
              // 如果响应不是JSON，使用状态文本
              const statusText = response.statusText || '未知错误';
              errorMsg += `: ${statusText}`;
            }

            throw new Error(errorMsg);
          }

          // 解析成功响应
          const data = await response.json();

          // 显示授权码
          authCodeElement.textContent = data.authorizationCode;
          generationTimeElement.textContent = new Date().toLocaleTimeString();
          showSuccess();
        } catch (err) {
          // 显示详细的错误信息
          showError(err.message || '发生未知错误');
        }
      }

      // 显示加载状态
      function showLoading() {
        loadingSection.style.display = 'flex';
        errorSection.style.display = 'none';
        codeSection.style.display = 'none';
        actionSection.style.display = 'none';
        instructions.style.display = 'none';
      }

      // 显示成功状态
      function showSuccess() {
        loadingSection.style.display = 'none';
        errorSection.style.display = 'none';
        codeSection.style.display = 'block';
        actionSection.style.display = 'flex';
        instructions.style.display = 'block';
      }

      // 显示错误状态
      function showError(message) {
        // 确保错误信息能正确显示
        errorMessageElement.textContent = message;
        loadingSection.style.display = 'none';
        errorSection.style.display = 'block';
        codeSection.style.display = 'none';
        actionSection.style.display = 'none';
        instructions.style.display = 'none';
      }

      // 事件监听器
      retryButton.addEventListener('click', function() {
        errorSection.style.display = 'none';
        usernameInput.focus();
      });

      newCodeButton.addEventListener('click', function() {
        showLoading();
        getAuthorizationCode(usernameInput.value.trim());
      });

      copyButton.addEventListener('click', function() {
        const text = authCodeElement.textContent;

        // 尝试使用现代的Clipboard API
        if (navigator.clipboard && navigator.clipboard.writeText) {
          navigator.clipboard.writeText(text)
            .then(() => {
              showCopySuccess();
            })
            .catch(err => {
              console.error('复制失败:', err);
              fallbackCopyText(text);
            });
        } else {
          fallbackCopyText(text);
        }
      });

      // 显示复制成功提示
      function showCopySuccess() {
        const originalText = copyButton.innerHTML;
        copyButton.innerHTML = '<i class="fas fa-check"></i> 已复制';
        copyButton.style.background = 'linear-gradient(90deg, #06d6a0 0%, #049c6b 100%)';

        setTimeout(() => {
          copyButton.innerHTML = originalText;
          copyButton.style.background = 'linear-gradient(90deg, #4361ee 0%, #3a0ca3 100%)';
        }, 2000);
      }

      // 传统复制方法
      function fallbackCopyText(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();

        try {
          const successful = document.execCommand('copy');
          if (successful) {
            showCopySuccess();
          } else {
            alert('复制失败，请手动复制');
          }
        } catch (err) {
          console.error('复制失败:', err);
          alert('复制失败，请手动复制');
        }

        document.body.removeChild(textarea);
      }

      // 按Enter键提交
      passwordInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
          loginBtn.click();
        }
      });
    });
  </script>
</body>
</html>



